import $getQuery from 'spore-kit-location/getQuery'
import $get from 'lodash/get'
import $getScript from './getScript'

let getJsPm = null
let banner = null

// 统一app
$(document).on('click', '[data-callapp]', async function (evt) {
	let actionName = $get(evt, 'currentTarget.dataset.trace', '')
	if (actionName) {
		$(document).trigger('trace', actionName)
	}
	let linkAction = $get(evt, 'currentTarget.dataset.callapp', '')
	callAppMethods.action(linkAction)
})

const callAppMethods = {
	// 初始化加载
	init() {
		if (!getJsPm) {
			getJsPm = new Promise(resolve => {
				let queryVerison = $getQuery(window.location.href, 'callapp_version')
				let version = queryVerison ? '/' + queryVerison : ''
				let src = `//s.yangshipin.cn/CCTVVideo/cctvh5-callapp${version}/cctvh5-callapp.min.js`
				$getScript({
					src,
					onLoad () {
						banner = window['cctvh5-callapp'].default
						resolve(banner)
					}
				})
			})
		}
		return getJsPm
	},
	// 打开app
	async action (address = '') {
		if (!banner) {
			if (navigator.userAgent.match(/MQQBrowser\/(\d+\.\d+)/i) && navigator.userAgent.match(/(android)\s([\d\.]+)/i)) {
				window.location.href = `cctvvideo://cctv.com/${address || 'HomeActivity'}`
			}
			await callAppMethods.init()
		}
		banner.action(`cctvvideo://cctv.com/${address || 'HomeActivity'}`)
	}
}

export default callAppMethods
